package per.example.arpproject.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import per.example.arpproject.model.ApiResult;


/**
 * @author yaozhang Li
 * @ TO DO
 * @creatTime 2022/6/10 11:50
 **/
@Slf4j
@ControllerAdvice
public class MyGlobalExceptionHandler {

    /**
     * RuntimeException 异常处理举例，其他同理，修改函数参数类型以及主机参数类即可
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler({RuntimeException.class})
    public ApiResult handleRunTimeException(final RuntimeException ex) {
        log.error("==> Error {} detected when request", ex.getMessage(), ex);
        return ApiResult.error(ex.getMessage());
    }

    /**
     * 异常处理，统一返回 服务内部错误
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler({Exception.class})
    public ApiResult handleUnknownException(final Exception ex) {
        log.error("==> Error {} detected when request", ex.getMessage(), ex);

        return ApiResult.error(ex.getMessage());
    }

}
